#ifndef MODBUSMASTER_H
#define MODBUSMASTER_H
#include <QModbusClient>
#include <QModbusDataUnit>
#include <QObject>
#include <QSerialPort>
#include <QModbusRtuSerialMaster>
#include <QModbusTcpClient>
#include <QMainWindow>
#include <sstream>
#include <string>
#include <iomanip>
namespace Ui {
class modbusSlave;
}

class modbusSlave : public QMainWindow
{
    Q_OBJECT

public:
    explicit modbusSlave(QWidget *parent1 = 0);
    ~modbusSlave();

    enum modbusConnection
    {
        Serial,
        Tcp
    };

    //@brief:初始化串口modbusslave
    //@param:端口 波特率 数据位 校验位 停止位
    //@ret: QModbusRtuSerialMaster对象构建成功返回 1
    //@birth:2019.4.17
    bool initModbusSerialSlave(QString portName, qint32 baudRate, QSerialPort::DataBits dataBits,
                         QSerialPort::Parity parity, QSerialPort::StopBits stopBits);

    //@brief:初始化 TCP modbusaster
    //@param: IP地址 端口
    //@ret: QModbusTcpClient对象构建成功返回 1
    //@birth:2019.4.17
    bool initModbusNetworkSlave(QString address,int port);

    //@brief:Connects the device to the Modbus network.
    //@param:
    //@ret: 成功返回 true
    //@birth:2019.4.17
    bool connectDevice();

    //@brief：向寄存器中写入数据 无法写入浮点数
    //@param:数据,开始地址,个数
    //@ret: 写入得到应答返回 1
    //@birth:2019.4.17
    bool writeRegisterData(QString str,int startAddress,int num);

    //@brief：读QModbusDataUnit::HoldingRegisters寄存器
    //@param:开始地址,个数
    //@ret: void
    //@birth:2019.4.17
    void readRegisterData(int startAddress,int num);


signals:

    void error_signal(QString errorString);

    void stateChanged_signal(int state);

    void readData_signal(int address,int value);


public slots:


    void handleDeviceError(QModbusDevice::Error newError);

    void onStateChanged(int state);//状态改变更新按钮显示

    void readyRead();

private slots:
    void on_connectButton_clicked();

    void on_sendButton_clicked();

    void on_receiveButton_clicked();

private:
    QModbusClient* m_slave;
    modbusConnection m_mode;
    Ui::modbusSlave *ui;

};

#endif // MODBUSMASTER_H









